// @ts-nocheck

// 配置信息
import config from "@climblee/uv-ui/libs/config/config.js"
// 颜色渐变相关
import * as colorGradient from "@climblee/uv-ui/libs/function/colorGradient.js"
// 防抖
import debounce from "@climblee/uv-ui/libs/function/debounce.js"
// 公共工具函数
import * as index from "@climblee/uv-ui/libs/function/index.js"
// 平台
import platform from "@climblee/uv-ui/libs/function/platform.js"
// 规则检验
import * as test from "@climblee/uv-ui/libs/function/test.js"
// 节流
import throttle from "@climblee/uv-ui/libs/function/throttle.js"
// 全局挂载引入http相关请求拦截插件
import Request from "@climblee/uv-ui/libs/luch-request"

const uv = {
  config,
  platform,
  test,
  ...index,
  ...colorGradient,
  debounce,
  throttle,
  http: new Request(),
}

export function useUv() {
  if (!uni.$uv) {
    uni.$uv = uv

    // 内部配置
    uv.setConfig({
      config: {
        unit: "rpx",
      },
    })
    // http 配置
    uv.http.setConfig(config => {
      config.baseURL = "https://8680qg9370.zicp.fun"
      config.timeout = 8000
      return config
    })
    // 请求拦截
    uv.http.interceptors.request.use(
      config => {
        if (config?.custom?.loading) {
          uni.showLoading()
        }
        // 可使用async await 做异步操作
        // 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
        config.data = config.data || {}
        // 根据custom参数中配置的是否需要token，添加对应的请求头
        if (config?.custom?.auth) {
          // 可以在此通过vm引用vuex中的变量，具体值在vm.$store.state中
          config.header.token = vm.$store.state.userInfo.token
        }
        return config
      },
      config => {
        // 可使用async await 做异步操作
        return Promise.reject(config)
      }
    )
    //  响应拦截
    uv.http.interceptors.response.use(
      res => {
        const custom = res.config?.custom
        if (custom?.loading) {
          uni.hideLoading()
        }
        const data = res.data
        if (data.code != 200) {
            uni.$uv.toast(data.msg)
            return Promise.reject(data)
        }
        return Promise.resolve(data.data)
      },
      err => {
        uni.hideLoading()
        console.log(err,9889)
        return Promise.reject(err)
      }
    )
  }

  return uni.$uv
}
